<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Cesium多层级3D Tiles动态加载</title>
    <script src="https://cesium.com/downloads/cesiumjs/releases/1.107/Build/Cesium/Cesium.js"></script>
    <link href="https://cesium.com/downloads/cesiumjs/releases/1.107/Build/Cesium/Widgets/widgets.css" rel="stylesheet">
    <style>
        html, body, #cesiumContainer {
            width: 100%;
            height: 100%;
            margin: 0;
            padding: 0;
            overflow: hidden;
        }
        .toolbar {
            position: absolute;
            top: 10px;
            left: 10px;
            z-index: 10;
            background-color: rgba(0, 0, 0, 0.7);
            color: white;
            padding: 10px;
            border-radius: 5px;
        }
        #fileTree {
            position: absolute;
            top: 10px;
            right: 10px;
            width: 300px;
            max-height: calc(100% - 20px);
            background-color: rgba(0, 0, 0, 0.7);
            color: white;
            padding: 10px;
            border-radius: 5px;
            overflow-y: auto;
            font-family: Arial, sans-serif;
        }
        .folder {
            cursor: pointer;
            padding: 5px;
            margin: 2px 0;
            background-color: rgba(255, 255, 255, 0.1);
        }
        .file {
            cursor: pointer;
            padding: 5px 5px 5px 20px;
            margin: 2px 0;
            background-color: rgba(255, 255, 255, 0.05);
        }
        .file:hover, .folder:hover {
            background-color: rgba(255, 255, 255, 0.2);
        }
        #loadingIndicator {
            position: absolute;
            bottom: 10px;
            left: 10px;
            background-color: rgba(0, 0, 0, 0.7);
            color: white;
            padding: 5px 10px;
            border-radius: 5px;
            display: none;
        }
    </style>
</head>
<body>
    <div id="cesiumContainer"></div>
    <div class="toolbar">
        <button id="refreshTree">刷新目录</button>
        <button id="clearTiles">清除瓦片</button>
    </div>
    <div id="fileTree"></div>
    <div id="loadingIndicator">加载中...</div>

    <script>
        // 替换为你的Cesium Ion令牌
        Cesium.Ion.defaultAccessToken = 'your_access_token_here';
        
        const viewer = new Cesium.Viewer('cesiumContainer', {
            terrainProvider: Cesium.createWorldTerrain()
        });
        
        const fileTree = document.getElementById('fileTree');
        const loadingIndicator = document.getElementById('loadingIndicator');
        let currentTileset = null;
        
        // 模拟目录结构数据（实际项目中应从服务器获取）
        const mockDirectoryStructure = {
            name: "根目录",
            isDirectory: true,
            children: [
                {
                    name: "城市区域",
                    isDirectory: true,
                    children: [
                        {
                            name: "市中心",
                            isDirectory: true,
                            children: [
                                { name: "buildings_tileset.json", isDirectory: false, type: "tileset" },
                                { name: "roads_tileset.json", isDirectory: false, type: "tileset" }
                            ]
                        },
                        {
                            name: "郊区",
                            isDirectory: true,
                            children: [
                                { name: "residential_tileset.json", isDirectory: false, type: "tileset" },
                                { name: "vegetation_tileset.json", isDirectory: false, type: "tileset" }
                            ]
                        }
                    ]
                },
                {
                    name: "地形数据",
                    isDirectory: true,
                    children: [
                        { name: "high_res_terrain.json", isDirectory: false, type: "tileset" },
                        { name: "water_bodies.json", isDirectory: false, type: "tileset" }
                    ]
                }
            ]
        };
        
        // 渲染目录树
        function renderDirectoryTree(node, parentElement) {
            const element = document.createElement(node.isDirectory ? "div" : "div");
            element.className = node.isDirectory ? "folder" : "file";
            element.textContent = node.name;
            
            if (node.isDirectory) {
                element.addEventListener("click", () => {
                    const childrenContainer = element.nextElementSibling;
                    if (childrenContainer) {
                        childrenContainer.style.display = childrenContainer.style.display === "none" ? "block" : "none";
                    }
                });
                
                const childrenContainer = document.createElement("div");
                node.children.forEach(child => {
                    renderDirectoryTree(child, childrenContainer);
                });
                
                parentElement.appendChild(element);
                parentElement.appendChild(childrenContainer);
            } else {
                // 如果是tileset文件，添加点击事件
                if (node.type === "tileset") {
                    element.addEventListener("click", () => {
                        loadTileset(node);
                    });
                }
                parentElement.appendChild(element);
            }
        }
        
        // 加载瓦片集
        function loadTileset(fileNode) {
            showLoadingIndicator();
            
            // 清除当前已加载的瓦片集
            if (currentTileset) {
                viewer.scene.primitives.remove(currentTileset);
                currentTileset = null;
            }
            
            // 构建瓦片集URL（根据实际项目调整）
            // 这里假设tileset.json文件位于服务器的tiles目录下
            const tilesetUrl = `tiles/${fileNode.name}`;
            
            currentTileset = new Cesium.Cesium3DTileset({
                url: tilesetUrl
            });
            
            viewer.scene.primitives.add(currentTileset);
            
            currentTileset.readyPromise.then(() => {
                hideLoadingIndicator();
                console.log(`瓦片集 ${fileNode.name} 加载成功`);
                viewer.zoomTo(currentTileset);
            }).catch(error => {
                hideLoadingIndicator();
                console.error(`瓦片集 ${fileNode.name} 加载失败:`, error);
                alert(`加载失败: ${error.message}`);
            });
        }
        
        // 显示加载指示器
        function showLoadingIndicator() {
            loadingIndicator.style.display = "block";
        }
        
        // 隐藏加载指示器
        function hideLoadingIndicator() {
            loadingIndicator.style.display = "none";
        }
        
        // 初始化目录树
        function initFileTree() {
            fileTree.innerHTML = "";
            renderDirectoryTree(mockDirectoryStructure, fileTree);
        }
        
        // 事件监听
        document.getElementById('refreshTree').addEventListener('click', initFileTree);
        document.getElementById('clearTiles').addEventListener('click', () => {
            if (currentTileset) {
                viewer.scene.primitives.remove(currentTileset);
                currentTileset = null;
            }
        });
        
        // 初始化
        initFileTree();
    </script>
</body>
</html>